#!/bin/python

#
#Xithyl, Test Driven Development for C
#Copyright (C) 2012  Stepan Henek
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import sys
import logging

loggers = { }

outs = [ ]
bstdout = sys.stdout
started = False

def __initLogger(name, level=logging.DEBUG, Format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', filters=[]):
    # Get the logger
    logger = logging.getLogger(name)
    # Set the level
    logger.setLevel(level)

    global outs
    # Add same logger for each stream
    for stream in outs:
        handler = logging.StreamHandler(stream)
        handler.setLevel(level)
        formatter = logging.Formatter(Format)
        handler.setFormatter(formatter)
        logger.addHandler(handler)

    # Apply all the filters
    map(logger.addFilter, filters)

    # Enable logger (if it was disabled by delLogger)
    logger.propagate = True

def addLogger(name, level=logging.DEBUG, Format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', filters=[]):
    # Extend loggers
    global loggers
    loggers[name] = {u'level':level, u'format':Format, u'filters':filters}

    global started
    if started:
        # The logging already started need to create and set the logger
        __initLogger(name, level, Format, filters)

def delLogger(name):
    # Remove from loggers
    global loggers
    del loggers[name]

    global started
    if started:
        # Disable the logger
        logger = logging.getLogger(name)
        logger.propagate = False

def start():
    # Already started?
    global started
    if started:
        return False

    # backup the stdout
    global bstdout
    bstdout = sys.stdout

    global outs
    class stdoutLog(object):
        def write(self, message):
            map(lambda x: x.write(message), outs)

    # Set the stdout
    sys.stdout = stdoutLog()

    # Set the loggers
    for key in loggers.keys():
        __initLogger(key, loggers[key][u'level'], loggers[key][u'format'], loggers[key][u'filters'])

    # Enable logging
    rootLogger = logging.getLogger()
    rootLogger.propagate = True

    started = True

    return True

def stop():

    # Already stopped?
    global started
    if not started:
        return False


    # Disable the logging
    rootLogger = logging.getLogger()
    rootLogger.propagate = False

    #Clear the loggers
    #for logger in logging.Logger.manager.loggerDict:
        #logging.Logger.manager.loggerDict[logger].handlers = []
    logging.Logger.manager.loggerDict = { }
    logging.shutdown()

    # restore the stdout
    global bstdout
    sys.stdout = bstdout

    started = False

    return True

def log(msg, name, level=logging.INFO):
    logger = logging.getLogger(name)
    logger.log(level, msg)

